#!/bin/sh
#(c) Copyright Barry Kauler 2007
#Now LGPL 2007
#run like this: # new2dir make install
#creates a directory one or two levels higher with the name of the package
#but slightly modified. For example source package has dir 'abiword-0.5.6'
#inside this you do the usual 'configure', 'make', then 'new2dir make install'
#and 'abiword-0.5.6-i486' directory gets created, with all installed files
#in it.
#120220 jemimah: fix to work with cmake (uncertain if will break anything else). ref: http://murga-linux.com/puppy/viewtopic.php?t=71767&start=420
#120602 updated installwatch to 0.7, got double hits from /tmp/pkginstall.list.
#130121 grab a .pot if it exists.
#131121 add support for different arches
#141011 unattended, for build scripts

usage() {
	echo
	echo "This script is used in the last step when installing a source"
	echo "or binary package. For example:"
	echo "# new2dir make install"
	echo
	echo "For an automated script call with 'newer2dir', for example"
	echo "newer2dir make install"
	echo "Exiting script."
}

if [ "${@}" != "make install" ];then
 usage
 exit
fi
auto=0 #0, manual, 1 , auto

echo $0|grep -q 'newer' && auto=1

TIMEOUT='-t 1'
ARCH=`uname -m`
if [ ! "$CPUTYPE" ];then
  if [ -f config.log ];then
  BuildCPU=`grep -m1 '^build_cpu='.*'' config.log |cut -f 2 -d "'"`
  HostCPU=`grep -m1 '^host_cpu='.*'' config.log |cut -f 2 -d "'"`
    if [ "$HostCPU" != "$BuildCPU" ];then
    echo "WARNING build_cpu='$BuildCPU' NOT host_cpu='$HostCPU'"
    fi
  CPUTYPE="$BuildCPU"
  fi
  if [ ! "$CPUTYPE" ];then
    if [ ! "$TIMEOUT" ];then
    CPUTYPE="i486"
    else
    CPUTYPE="$ARCH"
    fi
  else
  echo "Found '$CPUTYPE'"
  fi
fi
CPU="$CPUTYPE"
CURRDIR="`pwd`"
UPONE="`dirname "$CURRDIR"`"
PKGDIR="../`basename "$CURRDIR"`"
xPKGDIR="`basename "$CURRDIR"`"
if [ "`echo "$PKGDIR" | grep '[0-9]'`" = "" ];then
 PKGDIR="../../`basename "$UPONE"`"
 xPKGDIR="`basename "$UPONE"`"
fi
if [ "`echo "$PKGDIR" | grep '[0-9]'`" = "" ];then
 echo "$PKGDIR does not seem to be the package directory with version"
 echo "number. Unfortunately, some source package tarballs expand to a"
 echo "directory that does not have version number in it's name. SeaMonkey"
 echo "is an example of this, it expands to a directory named just 'mozilla'."
 echo "This script will create a package with the same name as the directory"
 echo "and it absolutely must have the version number in it which must commence"
 echo "with a numeric digit. So, you must now close this rxvt terminal window"
 echo "then rename the directory. For example, for SeaMonkey version 1.0.7"
 echo "rename the directory from 'mozilla' to 'seamonkey-1.0.7'"
 echo "A dash '-' must be used to separate the package name from version."
 echo "A directory name like 'seamonkey-alpha1' is NOT allowed as the version"
 echo "number must start with a numeric digit, example 'seamonkey-1.0.7alpha1'."
 echo "Exiting script."
 exit
fi

fixfilelistfunc() {
 #$1 is file to remove, as doesn't exist.
 echo " ...${1} has been deleted."
 grep -v "$1" /tmp/${EXE_PKGNAME}.files > /tmp/${EXE_PKGNAME}.files.tmp
 mv -f /tmp/${EXE_PKGNAME}.files.tmp /tmp/${EXE_PKGNAME}.files
}

if [ "$auto" -eq 0 ];then
	echo
	echo -en "\\033[1;31mStep 1" #red
	echo -e "\\033[0;39m"
	echo "It seems that the package directory is '$PKGDIR'"
	echo "If this is correct, just press ENTER key."
	echo "Otherwise, type the correct directory with relative address."
	echo " NOTE:"
	echo " This script will create a package with the same name as the directory"
	echo " and it absolutely must have the version number in it which must commence"
	echo " with a numeric digit, and name and version number must be separated by"
	echo " a dash '-', for example, 'seamonkey-1.0.7'."
	echo " A directory name like 'seamonkey-alpha1' is NOT allowed as the version"
	echo " number must start with a numeric digit, example 'seamonkey-1.0.7alpha1'."
	echo " If $PKGDIR is incorrect you must now exit with CTRL-C and close this"
	echo " rxvt terminal window then rename the directory."
	echo -n "Type response now: "
	read REPLY1
	[ ! "$REPLY1" = "" ] && PKGDIR="$REPLY1"
	if [ ! -d "$PKGDIR" ];then
	 echo
	 echo "$PKGDIR does not exist, exiting script."
	 exit
	fi
	echo "Okay, using $PKGDIR"

	echo
	echo -en "\\033[1;31mStep 2" #red
	echo -e "\\033[0;39m"
	echo "This Puppy is designed to run on a $ARCH. Normally this means"
	echo "that you have to specify 'build=$CPUTYPE-linux-gnu' (sometimes host=)"
	echo "Some packages do not have that configure option and compile for a"
	echo "specific CPU regardless what is in your PC."
	echo "If you have compiled for a $CPUTYPE, just press ENTER key."
	echo "Otherwise, enter the CPU type, examples: i386 i486 i686 amd64 x86_64 armv6"
	echo "(the i is required)."
	echo "If this is a script only with NO binarys type \"noarch\"."
	echo -n "Type response here: "
	read CPUTYPE
	[ "$CPUTYPE" = "" ] && CPUTYPE="$CPU"
	if [ "`echo -n "$CPUTYPE" | grep '^[a-zA-Z]'`" = "" ];then
	 echo "$CPUTYPE is not valid. Exiting."
	 exit
	fi
	echo "Okay, using $CPUTYPE"
fi

#would like to create different targets for exe, doc, dev, nls components...
EXE_TARGETDIR="${PKGDIR}-${CPUTYPE}" #relative path.
EXE_PKGNAME="`basename $EXE_TARGETDIR`"
RELPATH="`dirname $EXE_TARGETDIR`"
#difficult task, separate package name from version part... 
#not perfect, some start with non-numeric version info...
xNAMEONLY="`echo -n "$xPKGDIR" | sed -e 's/\-[0-9].*$//g'`"
#...if that fails, do it the old way...
[ "$xNAMEONLY" = "$xPKGDIR" ] && xNAMEONLY="`echo "$xPKGDIR" | cut -f 1 -d "-"`"
NAMEONLY="${RELPATH}/${xNAMEONLY}"
#abasename="`basename ${PKGDIR}`"
apattern="s/${xNAMEONLY}\\-//g"
VERONLY="`echo -n "$xPKGDIR" | sed -e "$apattern"`"
DOC_TARGETDIR="${NAMEONLY}_DOC-${VERONLY}-${CPUTYPE}"
DOC_PKGNAME="`basename $DOC_TARGETDIR`"
DEV_TARGETDIR="${NAMEONLY}_DEV-${VERONLY}-${CPUTYPE}"
DEV_PKGNAME="`basename $DEV_TARGETDIR`"
NLS_TARGETDIR="${NAMEONLY}_NLS-${VERONLY}-${CPUTYPE}"
NLS_PKGNAME="`basename $NLS_TARGETDIR`"

rm -rf "$EXE_TARGETDIR" 2>/dev/null
rm -rf "$DOC_TARGETDIR" 2>/dev/null
rm -rf "$DEV_TARGETDIR" 2>/dev/null
rm -rf "$NLS_TARGETDIR" 2>/dev/null

if [ "$auto" -eq 0 ];then
	echo
	echo -en "\\033[1;31mStep 3" #red
	echo -e "\\033[0;39m"
	echo "If you wish, you can split the final package up into separate"
	echo "packages for the 'executables', 'documentation', 'development' and"
	echo "'international' components."
	echo "If the package has shared libraries, it is recommended to at least"
	echo "create a seaparate 'development' package."
	echo "The idea here is to 'trim the fat' as much as possible so that you only"
	echo "have what is absolutely needed in the 'executables' PET package, but"
	echo "the extra components can be installed if needed."
	echo -en "\\033[1;31mWARNING: "
	echo -en "\\033[0;39m" 
	echo "The automatic splitting performed by this script may not be"
	echo "         perfect and you may have to modify the contents of the created"
	echo "         separate directories before the final step of converting them"
	echo "         to PET packages."
	echo
	echo "Just press ENTER key only to create one package only."
	echo "Or, type a number to choose which separate packages to create:"
	echo " 1 Just one package (directory) only"
	echo " 2 Create a separate 'development' package"
	echo " 3 Create separate 'development', 'documentation', 'international' pkgs"
	echo "Or, type a comma-separated list of the separate pkgs that you want to"
	echo " create, using keywords 'exe', 'dev', 'doc', 'nls'."
	echo " Example: exe,dev,doc  (in this example, nls component is left in the"
	echo " main package, that is, the exe component)."
	echo -n "Type response (just press ENTER if in doubt): "
	
	read SPLITPETS
	[ "$SPLITPETS" = "" ] && SPLITPETS="exe"
	[ "$SPLITPETS" = "1" ] && SPLITPETS="exe"
	[ "$SPLITPETS" = "2" ] && SPLITPETS="exe,dev"
	[ "$SPLITPETS" = "3" ] && SPLITPETS="exe,dev,doc,nls"
	EXESPLIT="";DOCSPLIT="";DEVSPLIT="";NLSSPLIT=""
	[ ! "`echo "$SPLITPETS" | grep 'exe'`" = "" ] && EXESPLIT="yes"
	[ ! "`echo "$SPLITPETS" | grep 'doc'`" = "" ] && DOCSPLIT="yes"
	[ ! "`echo "$SPLITPETS" | grep 'dev'`" = "" ] && DEVSPLIT="yes"
	[ ! "`echo "$SPLITPETS" | grep 'nls'`" = "" ] && NLSSPLIT="yes"
	[ ! "`echo "$SPLITPETS" | grep 'exe'`" = "" ] && mkdir "$EXE_TARGETDIR"
else
	EXESPLIT="";DOCSPLIT="";DEVSPLIT="";NLSSPLIT=""
	mkdir "$EXE_TARGETDIR"
	EXESPLIT="yes"
	DOCSPLIT="yes"
	DEVSPLIT="yes"
	NLSSPLIT="yes"
	SPLITPETS="exe,dev,doc,nls"
fi

if [ "$auto" = 0 ];then
	echo
	echo -en "\\033[1;31mStep 4" #red
	echo -e "\\033[0;39m"
	echo "The following line is about to be executed:"
	echo "# installwatch -o /tmp/pkginstall.list ${@}"
	echo "...this logs all file activity to /tmp/pkginstall.list"
	echo "This script will then determine all newly created directories"
	echo "and files and create '$EXE_TARGETDIR' with the new files."
	echo "(and optionally ${DEV_TARGETDIR}, ${DOC_TARGETDIR}, ${NLS_TARGETDIR})"
	echo -n "Press ENTER key to continue: "
	read goforit
	
	installwatch -o /tmp/pkginstall.list ${@}
else
	installwatch -o /tmp/pkginstall.list ${@}
fi
sync
#create list of installed files...
cat /tmp/pkginstall.list | grep '#success$' | tr -s '\t' | tr '&' ' ' | tr '\t' '&' | egrep '^[345]&open&|^0&chmod&' | grep --extended-regexp -v '&/dev/tty&|&/dev/null&|&/root/\.packages/|&/tmp/|&/root/\.icewm/|&/proc/|&/sys/|DotPupTmpDir|/\.myownmenuerc' | grep -E -v '&/initrd|&/mnt/' | cut -f 3 -d '&' | sort -u > ${RELPATH}/${EXE_PKGNAME}.files #120220 120602
#...list will only have created files, not created directories, so an empty
#   directory won't get recorded.

#bad if we miss out installing an empty directory...
cat /tmp/pkginstall.list | grep '#success$' | tr -s '\t' | tr '&' ' ' | tr '\t' '&' | grep '^0&mkdir&' | grep --extended-regexp -v '&/dev/tty&|&/dev/null&|&/root/\.packages/|&/tmp/|&/root/\.icewm/|&/proc/|&/sys/|DotPupTmpDir|/\.myownmenuerc' | grep -E -v '&/initrd|&/mnt/' | cut -f 3 -d '&' | sed -e 's/^\/\//\//g' > /tmp/${EXE_PKGNAME}.dirs

sync
#pick up created symlinks...
cat /tmp/pkginstall.list | grep '#success$' | tr -s '\t' | tr '&' ' ' | tr '\t' '&' | grep '^0&symlink&' | grep --extended-regexp -v '&/dev/tty&|&/dev/null&|&/root/\.packages/|&/tmp/|&/root/\.icewm/|&/proc/|&/sys/|DotPupTmpDir|/\.myownmenuerc' | grep -E -v '&/initrd|&/mnt/' | cut -f 4 -d '&' >> ${RELPATH}/${EXE_PKGNAME}.files

sync
#problem if there is a post-install script that moves or renames a file...
cat /tmp/pkginstall.list | grep '#success$' | tr -s '\t' | tr '&' ' ' | tr '\t' '&' | grep '^0&rename&' | grep --extended-regexp -v '&/dev/tty&|&/dev/null&|&/root/\.packages/|&/tmp/|&/root/\.icewm/|&/proc/|&/sys/|DotPupTmpDir|/\.myownmenuerc' | grep -E -v '&/initrd|&/mnt/' | cut -f 3,4 -d '&' | tr '\n' ' ' > /tmp/${EXE_PKGNAME}.moved.files
#find out if any installed file got moved/renamed...
if [ -s /tmp/${EXE_PKGNAME}.moved.files ];then
 for ONEMOVED in `cat /tmp/${EXE_PKGNAME}.moved.files`
 do
  ONEORIG="`echo -n "$ONEMOVED" | cut -f 1 -d '&'`"
  ONENEW="`echo -n "$ONEMOVED" | cut -f 2 -d '&'`"
  grep -v "$ONEORIG" ${RELPATH}/${EXE_PKGNAME}.files > /tmp/${EXE_PKGNAME}.files
  echo "$ONENEW" >> /tmp/${EXE_PKGNAME}.files
  sync
  mv -f /tmp/${EXE_PKGNAME}.files ${RELPATH}/${EXE_PKGNAME}.files
 done
fi


sync
echo
echo -en "\\033[1;31mStep 5" #red
echo -e "\\033[0;39m"
#fixfilelistfunc() uses this...
cp -af ${RELPATH}/${EXE_PKGNAME}.files /tmp/${EXE_PKGNAME}.files
#...a post-install script could delete files, which fixfilelistfunc fixes.
cat ${RELPATH}/${EXE_PKGNAME}.files |
while read ONEFILE
do
 ONEBASE="`basename "$ONEFILE"`"
 ONEPATH="`dirname "$ONEFILE"`"
 echo "Processing ${ONEFILE}"

 #strip the file...
 if [ ! -h "$ONEFILE" ];then #make sure it isn't a symlink
  [ ! "`file "$ONEFILE" | grep 'ELF' | grep 'shared object'`" = "" ] && strip --strip-debug "$ONEFILE"
  [ ! "`file "$ONEFILE" | grep 'ELF' | grep 'executable'`" = "" ] && strip --strip-unneeded "$ONEFILE"
 fi
 sync

 if [ "$NLSSPLIT" = "yes" ];then
  #find out if this is an international language file...
  if [ ! "`echo -n "$ONEFILE" | grep --extended-regexp '/locale/|/nls/|/i18n/'`" = "" ];then
   mkdir -p "${NLS_TARGETDIR}/${ONEPATH}"
   cp -af "$ONEFILE" "${NLS_TARGETDIR}/${ONEPATH}/" 2>/dev/null
   [ $? -ne 0 ] && fixfilelistfunc "$ONEFILE"
   continue
  fi
 fi

 if [ "$DOCSPLIT" = "yes" ];then
  #find out if this is a documentation file...
  if [ ! "`echo -n "$ONEFILE" | grep --extended-regexp '/man/|/doc/|/docs/|/info/|/gtk-doc/|/faq/|/manual/|/examples/|/help/|/htdocs/'`" = "" ];then
   mkdir -p "${DOC_TARGETDIR}/${ONEPATH}"
   cp -af "$ONEFILE" "${DOC_TARGETDIR}/${ONEPATH}/" 2>/dev/null
   [ $? -ne 0 ] && fixfilelistfunc "$ONEFILE"
   continue
  fi
 fi

 if [ "$DEVSPLIT" = "yes" ];then
  #find out if this is development file...
  if [ ! "`echo -n "$ONEFILE" | grep --extended-regexp '/include/|/pkgconfig/|/aclocal|/cvs/|/svn/'`" = "" ];then
   mkdir -p "${DEV_TARGETDIR}/${ONEPATH}"
   cp -af "$ONEFILE" "${DEV_TARGETDIR}/${ONEPATH}/" 2>/dev/null
   [ $? -ne 0 ] && fixfilelistfunc "$ONEFILE"
   continue
  fi
  #find *.so symlink files...
  #if [ -h "$ONEFILE" ];then #-h tests for symlink
   #if [ ! "`echo -n "$ONEFILE" | grep '\.so$'`" = "" ];then
    #mkdir -p "${DEV_TARGETDIR}/${ONEPATH}"
    #cp -af "$ONEFILE" "${DEV_TARGETDIR}/${ONEPATH}/" 2>/dev/null
    #[ $? -ne 0 ] && fixfilelistfunc "$ONEFILE"
    #continue
   #fi
  #fi
  #find various config files...
  if [ ! "`echo -n "$ONEBASE" | grep --extended-regexp '\-config$|config.sh$|Conf.sh$'`" = "" ];then
    mkdir -p "${DEV_TARGETDIR}/${ONEPATH}"
    cp -af "$ONEFILE" "${DEV_TARGETDIR}/${ONEPATH}/" 2>/dev/null
    [ $? -ne 0 ] && fixfilelistfunc "$ONEFILE"
    continue
  fi
  #all .a and .la files... and any stray .m4 files...
  if [ ! "`echo -n "$ONEBASE" | grep --extended-regexp '\.a$|\.la$|\.m4$'`" = "" ];then
    mkdir -p "${DEV_TARGETDIR}/${ONEPATH}"
    cp -af "$ONEFILE" "${DEV_TARGETDIR}/${ONEPATH}/" 2>/dev/null
    [ $? -ne 0 ] && fixfilelistfunc "$ONEFILE"
    continue
  fi  
 fi

 #anything left over goes into the main 'executable' package...
 if [ "$EXESPLIT" = "yes" ];then
  mkdir -p "${EXE_TARGETDIR}/${ONEPATH}"
  cp -af "$ONEFILE" "${EXE_TARGETDIR}/${ONEPATH}/" 2>/dev/null
  [ $? -ne 0 ] && fixfilelistfunc "$ONEFILE"
  #fix for empty directories...
  cat /tmp/${EXE_PKGNAME}.dirs |
  while read ANEWDIR
  do
   [ "`ls -1 $ANEWDIR`" = "" ] && mkdir -p ${EXE_TARGETDIR}${ANEWDIR}
  done
 fi
done

#130121 grab a .pot if it exists...
sync
pnPTN="/${xNAMEONLY}.pot"
if [ "`grep "$pnPTN" /tmp/${EXE_PKGNAME}.files`" = "" ];then
 FNDPOT="$(find ${CURRDIR}/ -type f -name "${xNAMEONLY}.pot" | head -n 1)"
 if [ "$FNDPOT" ];then
  mkdir -p ${EXE_TARGETDIR}/usr/share/doc/nls/${xNAMEONLY}
  cp -f "$FNDPOT" ${EXE_TARGETDIR}/usr/share/doc/nls/${xNAMEONLY}/
  echo "/usr/share/doc/nls/${xNAMEONLY}/" >> /tmp/${EXE_PKGNAME}.files
  echo "/usr/share/doc/nls/${xNAMEONLY}/${xNAMEONLY}.pot" >> /tmp/${EXE_PKGNAME}.files
 fi
fi

sync
cp -af /tmp/${EXE_PKGNAME}.files ${RELPATH}/${EXE_PKGNAME}.files

if [ "$auto" -ne 0 ];then
	echo "all done"
	exit
fi

echo
echo -en "\\033[1;31mFinished" #red
echo -e "\\033[0;39m"
echo "$EXE_TARGETDIR is now fully populated."
[ -d "$DEV_TARGETDIR" ] && echo "$DEV_TARGETDIR has also been populated."
[ -d "$DOC_TARGETDIR" ] && echo "$DOC_TARGETDIR has also been populated."
[ -d "$NLS_TARGETDIR" ] && echo "$NLS_TARGETDIR has also been populated."
echo "${RELPATH}/${EXE_PKGNAME}.files has a list of the installed files."
echo "You might want to go into it and trim the fat or whatever,"
echo "but basically it is now ready to be converted to a PET"
echo "package. Just do this:"
echo "# cd ${RELPATH}"
echo "# dir2pet $EXE_PKGNAME"

echo
echo "Press ENTER only to exit this script."
echo "Or, if you want the convenience, the 'dir2pet' script can be launched"
echo "right now -- press any character on the keyboard then ENTER."
echo -n "Type response here: "
read nextphase
[ "$nextphase" = "" ] && exit

cd ${RELPATH}
if [ -d ${xNAMEONLY}-${VERONLY}-${CPUTYPE} ];then
 dir2pet ${xNAMEONLY}-${VERONLY}-${CPUTYPE}
 echo -n "${xNAMEONLY}-${VERONLY}-${CPUTYPE}.pet created. Press ENTER to continue: "
 read domore
fi

if [ -d ${xNAMEONLY}_DEV-${VERONLY}-${CPUTYPE} ];then
 dir2pet ${xNAMEONLY}_DEV-${VERONLY}-${CPUTYPE}
 echo -n "${xNAMEONLY}_DEV-${VERONLY}-${CPUTYPE}.pet created. Press ENTER to continue: "
 read domore
fi

if [ -d ${xNAMEONLY}_DOC-${VERONLY}-${CPUTYPE} ];then
 dir2pet ${xNAMEONLY}_DOC-${VERONLY}-${CPUTYPE}
 echo -n "${xNAMEONLY}_DOC-${VERONLY}-${CPUTYPE}.pet created. Press ENTER to continue: "
 read domore
fi

if [ -d ${xNAMEONLY}_NLS-${VERONLY}-${CPUTYPE} ];then
 dir2pet ${xNAMEONLY}_NLS-${VERONLY}-${CPUTYPE}
 echo -n "${xNAMEONLY}_NLS-${VERONLY}-${CPUTYPE}.pet created. Press ENTER to continue: "
 read domore
fi

echo "All done."

###END###
